'use strict'
/**
 * 
 * 该文件中的接口为后台管理系统使用
 */
class user{
    constructor () {

    }
    async list (c) { // 用户列表展示
        let sqltext = `SELECT "userId","openId","userDay" FROM users`
        try {
            let r = await c.service.psql.query(sqltext,[]);
            c.send(JSON.stringify(r.rows))
            
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
    async get (c) { // 单个用户信息展示(不展示用户隐私信息)
        let sqltext = `SELECT "userId","openId","userDay" FROM users WHERE "userId"=$1`
        try {
            let r = await c.service.psql.query(sqltext,[c.param.id]);
            if (r.rowCount != 0) { 
                c.send(JSON.stringify(r.rows))
            } else {
                c.status(500).send('Show user failed!')
            }
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
    async post (c) {  // 创建新用户
        try {
            let sqltext = `INSERT INTO users("openId","userInfo","userDay")`  
                        +`VALUES($1,$2,$3)`;
            let data = JSON.parse(c.body);
            // 此处还需要根据具体提交的数据格式对userInfo进行处理，处理成数据库里对象的格式
            let r = r.service.psql.query(sqltext,[data.openId,data.userInfo,new Date().getTime()]) 
            if (r.rowCount != 0) { 
                c.send('Add user successfully!')
            } else {
                c.status(500).send('Add user failed!')
            }
        } catch (error) {
            c.status(500).send("Database's operations failed!")
        }
    }
    async delete (c) { // 删除用户
        try {
            let sqltext = `DELETE FROM users WHERE "userId"=$1`;
            // 此处还需要根据具体提交的数据格式对userInfo进行处理，处理成数据库里对象的格式
            let r = r.service.psql.query(sqltext,[c.param.id]) 
            if (r.rowCount != 0) { 
                c.send('Delete user successfully!')
            } else {
                c.status(500).send('Delete user failed!')
            }
        } catch (error) {
            c.status(500).send("Database's operations failed!")
        }
    }
}
module.exports = user;